package com.apache.passport.aop;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.springframework.aop.AfterReturningAdvice;

import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.passport.entity.LoginInfo;

/**
 * description: 登录信息方法后拦截 
 * @author Hou Dayu 创建时间：2014-12-19  
 * @Copyright(c)2014:
 */
public class LoginMethodAfterAdvice implements AfterReturningAdvice {
	private Logger log = Logger.getLogger(LoginMethodAfterAdvice.class);

	/**
	 * description:  将用户信息写入到文件中,5M为一个文件
	 * @param loginInfo
	 * @return  
	 * @author Hou Dayu 
	 * @update 2014-12-19
	 */
	private LoginInfo getLoginInfo(LoginInfo loginInfo) {
		if (Validator.isEmpty(loginInfo)) {
			return null;
		}
		return loginInfo;
	}

	/**
	 * returnValue 返回值
	 * TODO target:方法执行的结果.  
	 * 执行将用户登录日志写入数据库的操作
	 * @see org.springframework.aop.AfterReturningAdvice#afterReturning(java.lang.Object, java.lang.reflect.Method, java.lang.Object[], java.lang.Object)
	 */
	@Override
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		String targetName = target.getClass().getName();
		String methodName = method.getName();
		if (targetName.indexOf("com.apache.passport") != -1) {
			if (args.length > 0) {
				try {
					ParamsVo arguments = (ParamsVo) args[0];
					if ("execute".equals(methodName) && "true".equals(String.valueOf(returnValue))) {
						LoginInfo log = getLoginInfo((LoginInfo) arguments.getParams("loginInfo"));
						if (!Validator.isEmpty(log)) {
							LoginAopRunable runnable = new LoginAopRunable(log);
							PassportTheardPool.getInstance().saveLogger(runnable);
						}
					}
				} catch (Exception e) {
					log.error(e);
				}
			}
		}
	}
}
